package monsmon.game.parse;

import java.io.*;
import java.util.*;

import monsmon.util.FileLocator;

public class PreProccesser{

	public static final String segend = "%%SEGEND";

	private static String __gline(BufferedReader br){
		try{
			return br.readLine();
		}catch(Exception e){return null;}
	}

	private static String __get_seg(BufferedReader br){
		String s = "";
		String ln = "";
		while(true){
			ln = __gline(br);
			if(ln == null || ln.indexOf(segend) == 0){
				break;
			}
			s += ln + '\n';
		}
		return s;
	}

	private static LevelStrs __getlstr(FileDat fd, String ltag){
		LevelStrs l = fd.lvls.get(ltag);
		if(l == null){
			l = new LevelStrs();
			fd.lvls.put(ltag, l);
		}
		return l;
	}

	public static FileDat preproc(String file){
		BufferedReader f = null;
		try{
			InputStreamReader r = new InputStreamReader(
					FileLocator.get_read_file(file));
			f = new BufferedReader(r);
		}catch(Exception e){
			e.printStackTrace();
		}
		FileDat fd = new FileDat();
		while(true){
			String ln = __gline(f);
			if(ln == null) break;
			if(ln.indexOf("%%") == 0){
				if(ln.indexOf("%%SEGCTRL") == 0){
					String name = ln.substring(10, 
							ln.length() -1);
					String seg = __get_seg(f);
					__getlstr(fd, name).ctrl += seg;
				}else if(ln.indexOf("%%SEGMAP") == 0){
					String name = ln.substring(9, 
							ln.length() -1);
					String seg = __get_seg(f);
					__getlstr(fd, name).map += seg;
				}else if(ln.indexOf("%%SEGDEF") == 0){
					String name = ln.substring(9, 
							ln.length() -1);
					String seg = __get_seg(f);
					__getlstr(fd, name).def += seg;
				}else if(ln.indexOf("%%SEGMONS") == 0){
					String seg = __get_seg(f);
					fd.monsdef.append(seg);
				}else if(ln.indexOf("%%SEGGCRTL") == 0){
					String seg = __get_seg(f);
					fd.glbl.append(seg);
				}
			}
		}
		return fd;
		
	}	

}
